package com.globaldom.web.Civics;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.CivResource;
import com.globaldom.utils.Constants;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/getallcivswoupdate")
public class CivResourceGetAllController {
	public CivResourceGetAllController() {
	}

	private static final Logger log = Logger.getLogger(CivResourceGetAllController.class.getName());

	@RequestMapping(value = "/getallcivresources", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> getAllCivilian(HttpSession session, HttpServletRequest request) {

		Map<String, String> map = null;
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			map = new HashMap<String, String>();
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
			}
		map = MemCacheManager.getCivics(personID);
		 if (null != map)
		 return map;
		 else
		map = new HashMap<String, String>();

		PersistenceManager pmf = PMF.get().getPersistenceManager();
		try {

			Query query = pmf.newQuery(CivResource.class, "person==pid");
			query.declareParameters("String pid");
			List<CivResource> resources= ((List<CivResource>) query.execute(personID));
			
			for (CivResource civResource : resources) {
				map.put("res" + civResource.getResType(), String.valueOf(civResource.getResAvailable()));
			}
			 MemCacheManager.putCivics(personID, map);
		} finally {
			log.warning("Finished returning noudpate get all resource for person " + personID);
			pmf.close();
		}
		return map;

	}

}
